package com.csw.android.ffmpegtest.media.record

import android.media.AudioRecord
import androidx.lifecycle.LifecycleOwner
import com.csw.android.dev_utils.ex.CloseableEx.closeIgnoreException
import com.csw.android.ffmpegtest.media.base.RecordConfig
import com.csw.android.ffmpegtest.media.base.WAVHelper
import com.csw.android.ffmpegtest.media.record.base.BaseRecorder
import com.csw.android.ffmpegtest.media.record.base.IRecordListener
import java.io.RandomAccessFile

class WAVRecord(
    fp: String,
    lifecycleOwner: LifecycleOwner,
    listener: IRecordListener,
    recordConfig: RecordConfig = RecordConfig.fromMic()
) :
    BaseRecorder(fp, lifecycleOwner, listener, recordConfig) {
    private var startTime: Long = 0
    private var dataLength: Long = 0
    private val recordThread = RecordThread()
    private val runningPost = object : Runnable {
        override fun run() {
            onRunning(startTime, System.currentTimeMillis() - startTime, dataLength)
            if(working){
                mainHandler.postDelayed(this, 1000)
            }
        }
    }

    override fun start(): Boolean {
        if (super.start()) {
            onStart()
            startTime = System.currentTimeMillis()
            dataLength = 0
            working = true
            recordThread.start()
            //发出正在录制的事件
            mainHandler.postDelayed(runningPost, 1000)
            return true
        }
        return false
    }

    override fun stop(): Boolean {
        if (super.stop()) {
            working = false
            return true
        }
        return false
    }

    override fun release() {
        super.release()
        //标记工作状态位false，pcm接收线程会跳出循环，清理资源
        working = false
        //移除每秒通知回调
        mainHandler.removeCallbacks(runningPost)
    }

    private inner class RecordThread : Thread() {
        //录音控制对象
        private val audioRecord = AudioRecord(
            recordConfig.audioSource,
            recordConfig.sampleRateInHz,
            recordConfig.channelConfig,
            recordConfig.encoding,
            recordConfig.getMinBufferSize()
        )

        override fun run() {
            super.run()
            var os: RandomAccessFile? = null
            try {
                os = RandomAccessFile(getFilePath(), "rw")
                //写入44个字节作为wav文件头占位
                val headInfo = ByteArray(44)
                os.write(headInfo)
                dataLength += headInfo.size
                val buffer = ByteArray(recordConfig.getMinBufferSize())
                var read: Int
                audioRecord.startRecording()
                while (working) {
                    read = audioRecord.read(buffer, 0, buffer.size)
                    if (read > 0) {
                        os.write(buffer, 0, read)
                        dataLength += read
                    }
                }
                os.seek(0)
                WAVHelper.setHeadInfo(
                    headInfo,
                    (dataLength - 44).toInt(),
                    recordConfig.sampleRateInHz,
                    recordConfig.getChannelCount(),
                    recordConfig.encoding
                )
                os.write(headInfo)
                os.seek(os.length())
                onComplete()
            } catch (e: Exception) {
                onError(e)
            } finally {
                os.closeIgnoreException()
                audioRecord.stop()
                audioRecord.release()
            }
        }
    }


}